package com.example.chat.utils;

import com.alibaba.fastjson.JSON;
import com.example.chat.user.TokenInfo;
import com.example.chat.user.WeChatUser;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WechatUtil {
    private static final Logger log = LoggerFactory.getLogger(WechatUtil.class);
    private final static String appid = "wx0135051b38c87795";
    private final static String secret = "ec4387e074559d3007bd414673f2ecb8";

    public static WeChatUser getUserInfo(String code) throws Exception {
        HttpClient httpclient = HttpClients.createDefault();
        //用code交换token，code为扫码后微信服务器响应来的值
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&SECRET=" + secret + "&code=" + code + "&grant_type=authorization_code";
        //发请求
        HttpGet httpGet = new HttpGet(tokenUrl);
        String strResult = "";
        //接收返回的数据，转成utf-8格式
        HttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info("accesstoken结果 : {}", strResult);
        //处理数据，存到实体类CodeToken里面
        TokenInfo tokenInfo = JSON.parseObject(strResult, TokenInfo.class);

        //用token交换扫码人的个人信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenInfo.getAccess_token() + "&openid=" + tokenInfo.getOpenid() + "&lang=zh_CN";
        //向微信端发请求
        HttpGet httpGet1 = new HttpGet(userInfoUrl);
        String strResult1;
        //接收数据
        HttpResponse response1 = httpclient.execute(httpGet1);
        WeChatUser weChatUser = null;
        if (response1.getStatusLine().getStatusCode() == 200) {
            strResult1 = EntityUtils.toString(response1.getEntity(), "UTF-8");

            weChatUser = JSON.parseObject(strResult1, WeChatUser.class);
            log.info("个人信息：" + weChatUser);

        }
        return weChatUser;
    }
}


